import { defineConfig, PluginOption } from 'vite';
import path from 'path';
import vue from '@vitejs/plugin-vue';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import viteCompression from 'vite-plugin-compression';
import VueDevTools from 'vite-plugin-vue-devtools';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import tailwindcss from '@tailwindcss/vite';

export const isDev = process.env.NODE_ENV === 'development';
const resolve = (dir: string) => path.join(process.cwd(), dir);

function loadPlugins(): PluginOption[] {
  const plugins: PluginOption[] = [
    vue(),
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), 'src/components/Icon/SvgIcon/svg')],
      symbolId: 'icon-[dir]-[name]'
    }),
    viteCompression({
      disable: false,
      algorithm: 'gzip',
      ext: '.gz'
    }),
    Components({
      resolvers: [
        ElementPlusResolver({
          importStyle: 'css'
        })
      ],
      extensions: ['vue'],
      include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
      dts: 'src/types/components.d.ts'
    }),
    tailwindcss()
  ];

  if (process.env.npm_lifecycle_event === 'report') {
    plugins.push(VueDevTools());
  }
  return plugins;
}

export default defineConfig({
  server: {
    host: '0.0.0.0',
    port: 9528,
    strictPort: true
  },
  resolve: {
    alias: [
      {
        find: /~\//,
        replacement: resolve('src') + '/'
      },
      {
        find: /#\//,
        replacement: resolve('src/types') + '/'
      }
    ]
  },
  envPrefix: 'VITE_', // vite注入客户端的环境变量前缀
  css: {
    // postcss-module配置
    modules: {
      // css模块化配置
      // localsConvention: 'camelCaseOnly',
      // scopeBehaviour: 'local',
      // generateScopedName:
      // hashPrefix
      globalModulePaths: [
        // 不需要css模块化转换
      ]
    },
    preprocessorOptions: {
      // css全局参数
      scss: {
        // 导入全局参数
        // additionalData: '@use "~/styles/element/index.scss" as *;'
      }
    },
    devSourcemap: isDev // 是否开启css的sourceMap(文件索引)
  },
  plugins: loadPlugins(),
  optimizeDeps: {},

  build: {
    chunkSizeWarningLimit: 200,
    rollupOptions: {
      output: {
        manualChunks: id => {
          if (id.includes('node_modules')) {
            return 'vendor';
          }
        }
      }
    },
    sourcemap: isDev
  }
});
